(function () {
  'use strict';
  angular.module('controllers.oldOMDisplay', [
    'controllers.oldOMDisplay.oldSystemPerform',
    'controllers.oldOMDisplay.oldHealthy',
    'controllers.oldOMDisplay.pbossOm',
    'controllers.oldOMDisplay.operationDevelop',
    'controllers.oldOMDisplay.infoDispaly',
    'controllers.oldOMDisplay.upayQM',
    'controllers.omdisplay.businessOperation'
  ])
    .controller('oldOMDisplay', oldOMDisplay);

  function oldOMDisplay($rootScope, $filter, $timeout, COREDATA, CoreService,oldHealthyServer, chartOption, sumStatisticsServe, odService, TradePercentageServer, pbossOmServer, InfoViewService, operationAccuracyService, Restangular) {

    function initView() {
      if ($rootScope.oldInit) {
        return;
      }
      $rootScope.oldInit = true;
      var charts = {
        sysPerform: echarts.init(document.getElementById('sysPerformViewChart')),
        sysHealthy: echarts.init(document.getElementById('sysHealthyViewChart')),
        busAmount: echarts.init(document.getElementById('busAmountViewChart')),
        resUsage: echarts.init(document.getElementById('resUsageViewChart')),
        devCompletion: echarts.init(document.getElementById('devCompletionChart')),
        tradeRatio: echarts.init(document.getElementById('tradeRatioChart')),
        pbossQMTwo: echarts.init(document.getElementById('pbossQMTwoChart')),
        infoView: echarts.init(document.getElementById('infoViewGrowingChart')),
        accuracy: echarts.init(document.getElementById('accuracyViewChart'))
      };

      var options = {
        sysPerform: new SysPerfmOpt(),
        sysHealthy: angular.copy(chartOption.currentOp),
        resUsage: new HostResourceOpt(),
        devCompletion: {},
        tradeRatio: new TradeRatioChartOpt(),
        pbossQMTwo: new PbossQMTwoOpt(),
        infoView: new InfoViewCustomerOpt(),
        accuracy: new AccuracyChartOpt()
      };

      var now = new Date();
      var month = now.getMonth();
      var year = now.getFullYear();
      var day = now.getDate();
      var params = {
        sysPerform: {
          businessCode: '01',
          endTime: '',
          provinceCode: '200',
          startTime: '',
          systemCode: '11',
          timeType: '1'
        },
        sumStatistics: {
          'businessLine': [],
          'businessLineName': [],
          'channel': [],
          'organization': [],
          'provinceCode': [],
          'tradeStateCode': ['00'],
          'tradeStateName': [],
          'tradeTypeCode': [],
          'timeType': '5',
          'startTime': '2015-06-01',
          'startQuarter': '',
          'endTime': '2015-07-01',
          'endQuarter': '',
          'diffTime': 'true',
          'diffPro': '1',
          'seqPro': '0',
          'seqBus': '',
          'avg': '月'
        },
        devCompletion: {'startTime': '', 'endTime': ''},
        tradeRatio: {
          businessLine: [],
          endTime: '2015-07-01',
          provinceCodes: [],
          startTime: '2015-06-01',
          timeType: '5',
          unit: '0'
        },
        resUsage: {'startTime': '', 'endTime': '', timeType: '1', systemCode: '11', regionName: []},
        pbossQMTwo: {'startTime': '', 'endTime': ''},
        infoView: {'startTime': '', 'endTime': ''},
        accuracy: {'startTime': '', 'endTime': ''}
      };


      $timeout(function () {
        params.sysPerform.startTime = CoreService.dateFormat(new Date(year, month, day - 7), 'yyyy-MM-dd');
        params.sysPerform.endTime = CoreService.dateFormat(new Date(year, month, day), 'yyyy-MM-dd');
        options.sysPerform.grid = {x: 50, width: 200, height: 110, y: 20};
        options.sysPerform.legend = undefined;
        options.sysPerform.tooltip = {show: false};
        options.sysPerform.dataZoom = {show: false};

        Restangular.all('sas/OMdisplay/systemPerformance').post(params.sysPerform).then(function (res) {
          if (res.state !== '10000' || res.data.length === 0) {
            charts.sysPerform.setOption({series: {data: []}});
            return;
          }
          angular.forEach(res.data, function (item) {
            options.sysPerform.xAxis[0].data.push(item.time);
            options.sysPerform.series[0].data.push(item.responseTimeMax);
            options.sysPerform.series[1].data.push(item.responseTimeMin);
            options.sysPerform.series[2].data.push(item.currentAvgResponseTime);
            options.sysPerform.series[3].data.push(item.historyAvgResponseTime);
          });
          charts.sysPerform.setOption(options.sysPerform);
        });

      }, 100);

      $timeout(function () {
        options.sysHealthy.grid = {x: 50, width: 200, height: 110, y: 20};
        options.sysHealthy.legend = undefined;
        options.sysHealthy.tooltip = undefined;
        oldHealthyServer.current(charts.sysHealthy, options.sysHealthy, '');
      }, 200);

      $timeout(function () {
        params.sumStatistics.startTime = (now.getFullYear() - 1) + '-01-01';
        params.sumStatistics.endTime = now.getFullYear() + '-01-01';
        sumStatisticsServe.querySumStatistics(params.sumStatistics, function (res) {
          var option = new TradeSumStatOpt();
          if (res.state !== '10000' || !res.data || res.data.length === 0) {
            charts.busAmount.setOption({series: {data: []}});
            return;
          }
          angular.forEach(res.data, function (item) {
            option.xAxis[0].data.push(item.time);
            option.series[0].data.push(item.businessNum / 1000000);
            option.series[1].data.push(item.orderAmount / 100000000);
          });
          option.grid = {x: 50, width: 200, height: 110, y: 20};
          charts.busAmount.setOption(option);
        });
      }, 300);


      $timeout(function () {
        params.resUsage.startTime = CoreService.dateFormat(new Date(year, month, day - 7), 'yyyy-MM-dd');
        params.resUsage.endTime = CoreService.dateFormat(new Date(year, month, day), 'yyyy-MM-dd');
        Restangular.all('sas/OMdisplay/usageRate/dataBase').post(params.resUsage).then(function (res) {
          if (res.state !== '10000' || !res.data || !res.data.dataSpace || res.data.dataSpace.length === 0) {
            charts.resUsage.setOption({series: {data: []}});
            return;
          }
          var option = new HostResourceOpt();
          angular.forEach(res.data.dataSpace, function (item, key) {
            option.legend.data.push(item.hostIp);
            option.series[key] = {name: item.hostIp, data: [], type: 'bar'};
            angular.forEach(item.responseTime, function (subItem) {
              option.series[key].data.push(subItem);
            });
          });
          angular.forEach(res.data.dataSpace[0].time, function (item) {
            option.xAxis[0].data.push(item);
          });
          option.grid = {x: 50, width: 200, height: 110, y: 20};
          charts.resUsage.setOption(option);
        });
      }, 400);

      //$timeout(function () {
      //  params.devCompletion.startTime = now.getFullYear() + '-' + ((month - 1) > 10 ? (month - 1) : ('0' + (month - 1))) + '-01';
      //  params.devCompletion.endTime = now.getFullYear() + '-' + ((month) > 10 ? (month) : ('0' + (month))) + '-01';
      //  odService.dnDevelopNum.queryDevelopNum(params.devCompletion, function (res) {
      //    options.devCompletion = odService.dnDevelopNum.getEchartsData(res.data, '');
      //    options.devCompletion.title = {show: false};
      //    options.devCompletion.legend.show = false;
      //    options.devCompletion.grid = {x: 50, width: 200, height: 110, y: 20};
      //    options.devCompletion.tooltip = undefined;
      //    charts.devCompletion.setOption(options.devCompletion);
      //  });
      //}, 500);

      $timeout(function () {
        params.tradeRatio.startTime = (now.getFullYear() - 1) + '-01-01';
        params.tradeRatio.endTime = now.getFullYear() + '-01-01';
        TradePercentageServer.province(params.tradeRatio, function (res) {
          var tempItems = {};
          var arr;
          var sum = 0;
          if (res.state !== '10000' || res.data.length === 0) {
            charts.tradeRatio.setOption({series: {data: []}});
            return;
          }
          angular.forEach(COREDATA.PROVINCES, function (item) {
            tempItems[item.provinceCode] = {value: 0, provinceName: item.provinceName};
          });
          angular.forEach(res.data, function (item) {
            tempItems[item.provinceCode].value = Number(item.businessAmount);
          });
          arr = bubbleSort(tempItems);
          for (var i = 0; i < arr.length; i++) {
            sum = sum + Number(arr[i].value);
          }
          angular.forEach(arr, function (subItem, index) {
            var value = (subItem.value / (sum ? sum : 1) * 100).toFixed(2);
            var tempObj = {
              name: subItem.provinceName + '\n' + value + '%', //单项数据展示名称
              value: value,  //占比
              itemStyle: {  //显示样式设置
                normal: {
                  label: {
                    show: false
                  },
                  labelLine: {
                    show: false
                  }
                }
              }
            };
            //如果该项为前八项则显示标签名以及标签线
            if (index < 8) {
              tempObj.itemStyle.normal.label.show = true;
              tempObj.itemStyle.normal.labelLine.show = true;
            }
            options.tradeRatio.series[0].data.push(tempObj);
          });
          charts.tradeRatio.setOption(options.tradeRatio);
        });
      }, 600);

      $timeout(function () {
        params.pbossQMTwo.startTime = now.getFullYear() + '-' + ((month - 1) > 10 ? (month - 1) : ('0' + (month - 1))) + '-01';
        params.pbossQMTwo.endTime = now.getFullYear() + '-' + ((month) > 10 ? (month) : ('0' + (month))) + '-01';
        pbossOmServer.queryPbossBusiness(params.pbossQMTwo, function (res) {
          if (res.state !== '10000' || res.data.pageData.length === 0) {
            charts.pbossQMTwo.setOption({series: {data: []}});
            return;
          }
          angular.forEach(res.data.pageData, function (item) {
            options.pbossQMTwo.series[0].data.push(item.successRate);
            options.pbossQMTwo.yAxis[0].data.push(item.businessName);
          });
          options.pbossQMTwo.grid = {x: 80, width: 170, height: 110, y: 20};
          charts.pbossQMTwo.setOption(options.pbossQMTwo);
        });
      }, 700);

      $timeout(function () {
        params.infoView.startTime = (now.getFullYear() - 1) + '-' + ((month) > 10 ? (month) : ('0' + (month))) + '-01';
        params.infoView.endTime = now.getFullYear() + '-' + ((month) > 10 ? (month) : ('0' + (month))) + '-01';
        InfoViewService.queryCustomer(params.infoView, function (res) {
          if (res.state !== '10000' || res.data.length === 0) {
            charts.infoView.setOption({series: {data: []}});
            return;
          }
          angular.forEach(res.data, function (item) {
            options.infoView.xAxis[0].data.push(item.time);
            options.infoView.series[0].data.push(item.customerArrived / 10000);
            options.infoView.series[1].data.push(item.customerActive / 10000);
          });
          options.infoView.grid = {x: 50, width: 200, height: 110, y: 20};
          charts.infoView.setOption(options.infoView);
        });
      }, 800);

      $timeout(function () {
        params.accuracy.startTime = (now.getFullYear() - 1) + '-' + ((month) > 10 ? (month) : ('0' + (month))) + '-01';
        params.accuracy.endTime = now.getFullYear() + '-' + ((month) > 10 ? (month) : ('0' + (month))) + '-01';
        operationAccuracyService.queryOperationAccuracy(params.accuracy, function (res) {
          if (res.state !== '10000' || res.data.length === 0) {
            charts.accuracy.setOption({series: {data: []}});
            return;
          }
          angular.forEach(res.data, function (item, index) {
            if (index % 2 === 0) {
              options.accuracy.series[0].data.push(item.successRate);
              options.accuracy.xAxis[0].data.push(item.time);
            } else {
              options.accuracy.series[1].data.push(item.successRate);
            }
          });
          options.accuracy.grid = {x: 50, width: 200, height: 110, y: 20};
          charts.accuracy.setOption(options.accuracy);
        });
      }, 900);
    }

    $rootScope.$on('$stateChangeStart', function (event, toState) {
      if (toState.url === '/oldOMDisplay') {
        $rootScope.oldInit = false;
        $timeout(initView, 1000);
      }
    });

    $timeout(initView, 0);


    function bubbleSort(items) {
      var arr = [];
      //将传入的数组每一项重新推入新数组中
      for (var o in items) {
        if(items.hasOwnProperty(o)){
          arr.push(items[o]);
        }
      }
      //排序数组 这里传入一个自定义function 根据返回值 true or false 选择是否交换两个元素位置
      arr.sort(function (x, y) {
        return Number(y.value) - Number(x.value);
      });
      //返回排序后的数组
      return arr;
    }

    function SysPerfmOpt() {
      this.title = {show: false};
      this.tooltip = {show: false};
      this.animation = false;
      this.legend = {show: true, data: ['最低阀值', '最高阀值', '当前平均', '历史平均']};
      this.xAxis = [{
        type: 'category',
        boundaryGap: true,
        splitLine: false,
        axisLine: {onZero: false},
        data: [],
        splitArea: true
      }];
      this.yAxis = [{name: '响应时间', type: 'value', axisLabel: {formatter: '{value}s'}}];
      this.series = [
        {name: '最高阀值', type: 'line', smooth: true, data: [], symbolSize: 2, showAllSymbol: true},
        {name: '最低阀值', type: 'line', smooth: true, data: [], symbolSize: 2, showAllSymbol: true},
        {name: '当前平均', type: 'line', smooth: true, data: [], symbolSize: 2, showAllSymbol: true},
        {name: '历史平均', type: 'line', smooth: true, data: [], symbolSize: 2, showAllSymbol: true}
      ]
    }

    function TradeSumStatOpt() {
      this.animation = false;
      this.tooltip = {show: false};
      this.legend = {show: false, data: ['业务量', '交易金额']};
        this.xAxis = [{type: 'category', data: []}];
      this.yAxis = [{name: '业务量(百万笔)', type: 'value', splitLine: {show: false}}, {name: '交易金额(亿元)', type: 'value'}];
      this.series = [{name: '业务量', data: [], type: 'line'}, {name: '交易金额', data: [], type: 'bar', yAxisIndex: 1}];
    }

    function HostResourceOpt() {
      this.animation = false;
      this.tooltip = {show: false};
      this.legend = {show: false, data: []};
      this.xAxis = [{type: 'category', data: []}];
      this.yAxis = [{name: 'cpu使用率', type: 'value'}];
      this.series = [{name: 'cpu使用率', data: [], type: 'line'}];
    }

    function TradeRatioChartOpt() {
      this.title = {show: false};
      this.animation = false;
      this.series = [
        {
          name: '',
          type: 'pie',
          center: ['50%', '40%'],
          radius: ['0%', '55%'],
          data: [],
          clickable: false,
          itemStyle: {
            emphasis: {
              color: 'rgba(0,0,0,0)'
            }
          }
        }
      ];
    }

    function PbossQMTwoOpt() {
      this.title = {show: false};
      this.tooltip = {show: false};
      this.legend = {show: false, data: []};
      this.xAxis = [{type: 'value', axisLabel: {formatter: '{value} %'}, name: '业务成功率', min: 90, max: 100}];
      this.yAxis = [{type: 'category', data: []}];
      this.series = [{name: '成功率', type: 'bar', data: [], barMinHeight: 3}];
    }

    function InfoViewCustomerOpt() {
      this.title = {show: false};
      this.tooltip = {show: false};
      this.legend = {data: ['客户到达数', '客户活跃数']};
      this.xAxis = [{type: 'category', name: '', data: []}];
      this.yAxis = [{type: 'value', name: '人数(万)'}];
      this.series = [{name: '客户到达数', type: 'line', data: []}, {name: '客户活跃数', type: 'line', data: []}];
    }

    function AccuracyChartOpt() {
      this.title = {show: false};
      this.tooltip = {show: false};
      this.legend = {data: ['省公司', '银行']};
      this.xAxis = [{type: 'category', name: '', data: []}];
      this.yAxis = [{type: 'value', name: '成功率', axisLabel: {formatter: '{value}%'}, min: 90, max: 100}];
      this.series = [{name: '省公司', type: 'bar', data: []}, {name: '银行', type: 'bar', data: []}];
    }
  }
}());